package gamePlus;

import game.Player;
import gamePlus.server.RoundResults;

import java.util.HashMap;
import java.util.LinkedList;

public class GameScore {
	class PlayerScore {
		class MatchScore {
			LinkedList<RoundScore> rounds;
			
			public MatchScore() {
				rounds = new LinkedList<>();
			}
		}
		class RoundScore {
			int points;
			int cumsum;
			
			public RoundScore(int points, int cumsum) {
				this.points=points;
				this.cumsum = cumsum+points;
			}
		}
		

		LinkedList<MatchScore> matches;
		
		public PlayerScore() {
			matches = new LinkedList<>();
		}
		
		public void addResult(int points) {
			if(matches.isEmpty()||matches.getLast().rounds.size()==settings.roundCount)
				matches.add(new MatchScore());
			int cumsum;
			int lastPoints;
			if(matches.getLast().rounds.isEmpty()) {
				cumsum=0;
				lastPoints=0;
			}
			else {
				cumsum=matches.getLast().rounds.getLast().cumsum;
				lastPoints = matches.getLast().rounds.getLast().points;
			}
			if(points==50&&lastPoints>0)
				points = lastPoints+points;
			matches.getLast().rounds.add(new RoundScore(points, cumsum));
		}
	}
	
	HashMap<String, PlayerScore> playerScores;
	GameSettings settings;
	
	public GameScore(GameSettings settings, LinkedList<Player> players) {
		playerScores = new HashMap<>();
		this.settings = settings;
		for(Player player: players)
			playerScores.put(player.getName(), new PlayerScore());
	}
	
	public void addResult(RoundResults results) {
		for(int i=0;i<results.playerResults.length;i++) {
			playerScores.get(results.playerResults[i].playerName).addResult(results.playerResults[i].points);
		}
	}
	
	public boolean gameEnded(String playerName) {
		return playerScores.get(playerName).matches.size()==settings.matchCount&&playerScores.get(playerName).matches.getLast().rounds.size()==settings.roundCount;
	}
}
